const { query, update, get } = require('../../helper/db');
const { ok, door } = require('../../helper/util');

/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup 好友
 * @api {POST} api/friend/del 删除好友
 * @apiName api/friend/del
 * @apiExample {js} axios 例子:
 *  axios.post('http://39.105.38.34:8080/api/friend/del', {
 *    relationID: 1,
 *  });
 * @apiParam  {String} relationID 要删除的好友关系表的 ID
 * @apiSuccess (请求成功) {Null} data 删除成功后不返回数据
 * @apiuse  ErrorResponse
 */

module.exports = async ctx => {
  var token = ctx.headers.authorization;
  var params = ctx.request.body;
  var user = await door(token);
  // 属于我的关系数据
  var myRelation = await get('relation_ship', params.relationID);
  // 更新我的关系数据
  var updatedMyRelation = await update('relation_ship', { ...myRelation, status: 3 });
  // 获取对方的关系数据
  var otherRelation = (await query(
    'select * from relation_ship where userid = ? and friendID = ?',
    [updatedMyRelation.friendID, updatedMyRelation.userid]
  ))[0];
  // 更新对方的关系数据
  await update('relation_ship', { ...otherRelation, status: 3 });

  ctx.body = ok(null);
}